//
//  RegisterController.m
//  NPS
//
//  Created by jadd on 15/12/14.
//  Copyright © 2015年 jadd. All rights reserved.
//

#import "RegisterController.h"
#define kphone      0
#define kpwd        1
#define kcode       2


#define TEXT_Field CGRectMake(105, 10, self.view.bounds.size.width - 105, 40.0f)

#define TEXT_Field_Code CGRectMake(105, 10, self.view.bounds.size.width - 240, 40.0f)
#define BTN_Field_Code CGRectMake(self.view.bounds.size.width - 120, 10, 100, 40.0f)

@interface RegisterController ()

@end

@implementation RegisterController
@synthesize  array;
@synthesize tempValues,textFieldBeingEdited;
@synthesize phone,pwd,code;
@synthesize codeBtn;

-(IBAction)codeAction:(id)sender{
    __block int timeout=60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                codeBtn.backgroundColor = [UIColor colorWithHexString:K_Global_ColorHexString_Store];
                [codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                codeBtn.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            //int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //NSLog(@"____%@",strTime);
                codeBtn.backgroundColor = BButtonTypeDefault;
                [codeBtn setTitle:[NSString stringWithFormat:@"重新发送(%@)",strTime] forState:UIControlStateNormal];
                codeBtn.userInteractionEnabled = NO;
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
    
}




-(IBAction)textFieldDone:(id)sender{
    
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.textFieldBeingEdited = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSNumber *tagAsNum = [[NSNumber alloc] initWithInteger:textField.tag];
    if(textField.text != nil){
        [tempValues setObject:textField.text forKey:tagAsNum];
    }
    
}

- (BOOL) validateMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}


-(BOOL) checkValuesInTextField {
    if (phone == nil) {
        [Config showMessage:@"请输入您的手机号码!"];
        return false;
    }
    else if(![self validateMobile: phone])
    {
        [Config showMessage:@"手机号码格式不正确!"];
        return false;
    }
    else if (pwd == nil) {
        
        [Config showMessage:@"请输入您的密码!"];
        return false;
    }
    else if ([pwd lengthOfBytesUsingEncoding:NSUTF8StringEncoding] < 6){
        [Config showMessage:@"新密码位数不能少于六位!"];
        
        return false;
    }
    else if (code == nil) {
        [Config showMessage:@"请输入您的验证码!"];
        
        return false;
    }
    else {
        return true;
    }
    
}



-(IBAction)loginPressed:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"");
    }];
}

-(void)backButtonPressed{
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"");
    }];
    //[self.navigationController popViewControllerAnimated:YES];
}

//注册事件
-(IBAction)registerAction:(id)sender
{
    if (textFieldBeingEdited != nil)
    {
        NSNumber *tagAsNum= [[NSNumber alloc] initWithInteger:textFieldBeingEdited.tag];
        [tempValues setObject:textFieldBeingEdited.text forKey: tagAsNum];
        
    }
    
    for (NSNumber *key in [tempValues allKeys])
    {
        switch ([key intValue]) {
            case kphone:
                //除去空格和下划线
                phone = [[tempValues objectForKey:key] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                break;
            case kpwd:
                pwd = [[tempValues objectForKey:key] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                break;
            case kcode:
                code = [[tempValues objectForKey:key] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                break;
            default:
                break;
        }
    }
    
    
    bool result = [self checkValuesInTextField];
    if(!result)
    {
        NSLog(@"1");
    }
    else
    {
        NSLog(@"%@,%@,%@",phone,pwd,code);
        [self dismissViewControllerAnimated:NO completion:^{
            NSLog(@"");
        }];
    }
}


- (void)viewDidLoad {
    
    //self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tempValues = [[NSMutableDictionary alloc] init];
    dispatch_async(dispatch_get_main_queue(), ^{
        
    });
    self.title = @"立即注册";
    self.tableView.scrollEnabled =NO;
    
    self.array = [[NSMutableArray alloc] initWithObjects:@"手机号",@"密码", @"验证码",nil];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom] ;
    button.frame = CGRectMake(0, 0, K_Global_BackButton_Width, K_Global_BackButton_Height);
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [button setImage:[UIImage imageNamed:@"back_white_on"] forState:UIControlStateNormal];
    //[button setImage:[UIImage imageNamed:@"back_white_on"] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = leftButton;
    [super viewDidLoad];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 3;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 60;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, K_ScreenWidth, 100.0f)];
    footView.backgroundColor = CLEAR;
    footView.tintColor = CLEAR;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setFrame:CGRectMake(K_ScreenWidth *0.04, 40, (K_ScreenWidth -(K_ScreenWidth *0.04*2)), 45.0f)];
    
    [button.layer setMasksToBounds:YES];
    [button.layer setCornerRadius:5.0f];
    [button.layer setBorderWidth:0.5f];
    [button.layer setBorderColor:DEFAULT_LINE_GRAY_COLOR.CGColor];
    button.backgroundColor = [UIColor colorWithHexString:K_Global_ColorHexString_Store];
    
    [button setTitle:@"注 册" forState:UIControlStateNormal];
    UIFont *font = [UIFont systemFontOfSize:20.0];
    
    [button addTarget:self action:@selector(registerAction:) forControlEvents:UIControlEventTouchUpInside];
    [button.titleLabel setFont:font];
    [button setTitleColor:WHITE forState:UIControlStateNormal];
    [footView addSubview:button];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [loginBtn setFrame:CGRectMake(K_ScreenWidth *0.04, 120, (K_ScreenWidth -(K_ScreenWidth *0.04*2)), 45.0f)];
    [loginBtn setTitle:@"" forState:UIControlStateNormal];
    
    NSString *str =  @"没有账号，赶快去登录";
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str];
    [string addAttribute:NSForegroundColorAttributeName value:GRAY range:NSMakeRange(0, 8)];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:K_Global_ColorHexString_Store] range:NSMakeRange(8, 2)];
    [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18.0] range:NSMakeRange(0, string.length)];
    
    [loginBtn setAttributedTitle:string forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(loginPressed:) forControlEvents:UIControlEventTouchUpInside];
    [loginBtn.titleLabel setFont:[UIFont systemFontOfSize:20.0]];
    [loginBtn setTitleColor:WHITE forState:UIControlStateNormal];
    [footView addSubview:loginBtn];
    
    
    return footView;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 180;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"TJCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    NSUInteger row = [indexPath row];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
        CGRect cect = TEXT_Field;
        if(row == kcode)
        {
            cect = TEXT_Field_Code;
        }
        UITextField *txtField = [[UITextField alloc] initWithFrame:cect];
        txtField.clearButtonMode = UITextFieldViewModeWhileEditing;
        txtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        txtField.font = [UIFont systemFontOfSize:18];
        
        txtField.textColor = GRAY;
        [txtField setDelegate:self];
        
        [txtField addTarget:self action:@selector(textFieldDone:) forControlEvents: UIControlEventEditingDidEndOnExit];
        [cell.contentView addSubview:txtField];
        
    }
    
    
    cell.textLabel.text = [self.array objectAtIndex:row];
    
    UITextField *textField = nil;
    
    
    for (UIView *oneView in cell.contentView.subviews)
    {
        if ([oneView isMemberOfClass:[UITextField class]])
            textField = (UITextField *)oneView;
        //textField.secureTextEntry = YES;
        
    }
    textField.tag = row;
    //label.text = [array objectAtIndex:row];
    NSNumber *rowAsNum = [[NSNumber alloc] initWithInteger:row];
    switch (row) {
        case kphone:
            textField.placeholder = @"手机号码";
            [textField setValue:[UIFont boldSystemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
            //[textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
            if ([[tempValues allKeys] containsObject:rowAsNum])
                textField.text = [tempValues objectForKey:rowAsNum];
            else
                textField.text = @"";
            break;
        case kpwd:
            textField.placeholder = @"密码";
            [textField setValue:[UIFont boldSystemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
            if ([[tempValues allKeys] containsObject:rowAsNum])
                textField.text = [tempValues objectForKey:rowAsNum];
            else
                textField.text =  @"";
            break;
        case kcode:
            textField.placeholder = @"验证码";
            [textField setValue:[UIFont boldSystemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
            if ([[tempValues allKeys] containsObject:rowAsNum])
                textField.text = [tempValues objectForKey:rowAsNum];
            else
                textField.text =  @"";
            break;
        default:
            break;
    }
    if (textFieldBeingEdited == textField)
        textFieldBeingEdited = nil;
    


    if(row == kcode)
    {
        codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [codeBtn setFrame:BTN_Field_Code];
        [codeBtn.layer setMasksToBounds:YES];
        [codeBtn.layer setCornerRadius:5.0f];
        [codeBtn.layer setBorderWidth:0.5f];
        [codeBtn.layer setBorderColor:DEFAULT_LINE_GRAY_COLOR.CGColor];
        codeBtn.backgroundColor = [UIColor colorWithHexString:K_Global_ColorHexString_Store];
        
        [codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        UIFont *font = [UIFont systemFontOfSize:14.0];
        [codeBtn addTarget:self action:@selector(codeAction:) forControlEvents:UIControlEventTouchUpInside];
        [codeBtn.titleLabel setFont:font];
        [codeBtn setTitleColor:WHITE forState:UIControlStateNormal];
        //[codeBtn setTitleColor:WHITE forState:UIControlStateNormal];
        //[codeBtn setTitleColor:GRAY forState:UIControlStateHighlighted];
        
        [cell.contentView addSubview:codeBtn];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}






@end
